<template>
  <view class="purchase-record-page">
    <!-- 顶部导航（固定定位） -->
    <view class="top-bar">
      <view class="back-btn" @click="navigateBack">
        <image 
          class="back-icon" 
          src="/static/icons/left.png" 
          mode="widthFix"
        ></image>
      </view>
      <text class="page-title">购买记录</text>
    </view>

    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text>加载中...</text>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-else-if="recordData.length === 0">
      <image class="empty-icon" src="/static/empty.png" mode="aspectFit"></image>
      <text class="empty-text">暂无购买记录</text>
    </view>

    <!-- 购买记录列表（Vue 2 兼容语法：用 && 替代 ?.） -->
    <view class="record-list" v-else>
      <view 
        class="record-item" 
        v-for="(item, index) in recordData" 
        :key="item && item.orderId ? item.orderId : index"  
        @click="goToDetail(item)"
        v-if="item"  
      >
        <!-- 商品图标（固定默认图标） -->
        <image 
          class="item-icon" 
          src="/static/icons/member-icon.png" 
          mode="aspectFill"
        ></image>
        
        <!-- 内容区（用 && 安全访问 buyTime） -->
        <view class="item-content">
          <text class="item-name">开通会员</text>
          <text class="time">{{ item && item.buyTime ? formatBuyTime(item.buyTime) : '' }}</text>
        </view>
        
        <!-- 金额（用 && 和 || 兜底） -->
        <text class="amount" style="color: #f00;">-{{ item && item.amount !== undefined ? item.amount : 0 }}元</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getOrderByUserId } from '@/api/user.js'
export default {
  data() {
    return {
      userId: null,
      loading: false,
      recordData: []  // 初始化空数组，兼容 Vue 2 渲染
    };
  },
  onLoad(val) {
    // Vue 2 兼容：用 typeof 判断 val 存在，避免直接访问 val.userId 报错
    this.userId = typeof val !== 'undefined' && val.userId ? val.userId : null;
    if (!this.userId) {
      uni.showToast({ title: '用户ID不存在', icon: 'none' });
      setTimeout(() => uni.navigateBack(), 1000);
      return;
    }
    this.getBuyOrder();
  },
  methods: {
    getBuyOrder() {
      this.loading = true;
      getOrderByUserId({ userId: this.userId })
        .then(res => {
          if (res.code === 200) {
            // 过滤空项：用传统循环替代 filter（兼容所有场景）
            const validData = [];
            const rawData = typeof res.data !== 'undefined' ? res.data : [];
            for (let i = 0; i < rawData.length; i++) {
              const item = rawData[i];
              // 只保留有效对象（排除 null/undefined/非对象类型）
              if (item && typeof item === 'object') {
                validData.push(item);
              }
            }
            this.recordData = validData;
          } else {
            uni.showToast({ title: res.msg || '获取记录失败', icon: 'none' });
            this.recordData = [];
          }
        })
        .catch(err => {
          console.error('获取购买记录异常:', err);
          uni.showToast({ title: '网络错误', icon: 'none' });
          this.recordData = [];
        })
        .finally(() => {
          this.loading = false;
        });
    },

    formatBuyTime(timeStr) {
      // Vue 2 兼容：多重判断确保参数有效
      if (typeof timeStr !== 'string' || timeStr.length === 0) {
        return '';
      }
      const timeParts = timeStr.split('T');
      // 判断分割后是否有日期和时间部分
      if (timeParts.length < 2) {
        return '';
      }
      const datePart = timeParts[0];
      const timePart = timeParts[1];
      
      const dateParts = datePart.split('-');
      // 判断日期格式是否正确（年-月-日）
      if (dateParts.length < 3) {
        return '';
      }
      const month = parseInt(dateParts[1], 10);
      const day = parseInt(dateParts[2], 10);
      // 判断月份和日期是否为有效数字
      if (isNaN(month) || isNaN(day)) {
        return '';
      }
      const shortDate = `${month}-${day}`;
      
      const timePartsShort = timePart.split(':');
      // 判断时间格式是否正确（时:分:秒）
      if (timePartsShort.length < 2) {
        return '';
      }
      const shortTime = `${timePartsShort[0]}:${timePartsShort[1]}`;
      
      return `${shortDate} ${shortTime}`;
    },

    navigateBack() {
      uni.navigateBack();
    },

    goToDetail(item) {
      // Vue 2 兼容：判断 item 存在再执行
      if (!item || typeof item !== 'object') {
        return;
      }
      uni.navigateTo({
        url: `/pages/zj/PurchaseDetails?orderId=${item.orderId}`
      });
    }
  }
};
</script>

<style scoped>
/* 样式部分完全不变 */
.purchase-record-page {
  background-color: #fff;
  min-height: 100vh;
  padding-top: 44px;
}

.top-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 15px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
}
.back-btn {
  width: 44px;
  height: 44px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.back-icon {
  width: 16px;
  height: 16px;
}
.page-title {
  font-size: 17px;
  font-weight: bold;
  color: #333;
  flex: 1;
  text-align: center;
  margin: 0 44px;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300rpx;
  color: #999;
  font-size: 16px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #999;
}
.empty-icon {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
  opacity: 0.5;
}
.empty-text {
  font-size: 16px;
}

.record-list {
  padding: 0 15px 15px;
}
.record-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
  cursor: pointer;
}
.record-item:active {
  background-color: #f5f5f5;
}
.item-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  margin-right: 10px;
}
.item-content {
  flex: 1;
  display: flex;
  align-items: center;
}
.item-name {
  font-size: 16px;
  color: #333;
  margin-right: 12px;
}
.time {
  font-size: 14px;
  color: #999;
}
.amount {
  font-size: 16px;
  font-weight: bold;
}
</style>